class UserCourse < ActiveRecord::Base
  before_create  :set_create_user

  belongs_to :user
  belongs_to :course, :counter_cache => true 
  
  #   
  #   find appointed user study appointed course log
  #
  def self.user_learned_course(user_id, course_id)
    UserCourse.find_or_create_by_user_id_and_course_id(user_id, course_id)
  end

  def  set_create_user
    UserCourse.find_by_user_id_and_course_id(user.id,course.id).nil??self.ownned_flag=1:nil
  end

  #
  #   update user study data info
  #
  def self.update_study_info(user_course,study_time)
    user_course.sessiontime += study_time
    user_course.save!
  end

  #
  #   caculate study course progress
  #
  def self.calculate_progress(user_course)
    user_id = user_course.user_id
    course = user_course.course
    course_id = user_course.course_id
    items_count = course.items_count
    return if items_count == 0
    total_progress = 0
    user_items = UserItem.user_learned_items(user_id, course_id)
    user_items.each {|user_item| total_progress += user_item.progress}
    user_course.progress = total_progress.div items_count
    user_course.save!
  end
end
